package com.doris.lucene;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

/**
 * 文件及目录读取
 * 
 * @author root
 *
 */
public class FileSearcher {

	private static final Logger LOGGER = Logger.getLogger(DocumentParseThread.class);
	/**
	 * 递归爬取文件，并按照后缀名计数
	 * 
	 * @param dir 爬取目录
	 * @return 后缀名和文件数的映射
	 */
	private Map<String, Integer> searchAndCount(String dir) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		File serachDir = new File(dir);
		searchAndCount(serachDir, map);
		return map;
	}

	/**
	 * 递归爬取文件
	 * 
	 * @param dir 爬取目录
	 * @return 文件路径集合
	 */
	public List<String> search(String dir) {
		List<String> files = new ArrayList<String>();
		File serachDir = new File(dir);
		search(serachDir, files);
		return files;
	}

	private void search(File serachDir, List<String> files) {
		if (serachDir.isDirectory()) {
			for (File file : serachDir.listFiles()) {
				search(file, files);
			}
		} else {
			String name = serachDir.getName();
			String suffix = name.substring(name.lastIndexOf(Constants.DOT) + 1);
			if (LuceneProperties.getSuffixs().contains(suffix)) {
				files.add(serachDir.getAbsolutePath());
			}
		}
	}

	private void searchAndCount(File serachDir, Map<String, Integer> map) {
		if (serachDir.isDirectory()) {
			for (File file : serachDir.listFiles()) {
				searchAndCount(file, map);
			}
		} else {
			String name = serachDir.getName();
			String suffix = name.substring(name.lastIndexOf(Constants.DOT) + 1);
			if (LuceneProperties.getSuffixs().contains(suffix)) {
				if (map.get(suffix) == null) {
					map.put(suffix, 1);
				} else {
					map.put(suffix, map.get(suffix) + 1);
				}
			}
		}
	}

	public static void main(String[] args) {
		List<Object> searchDirs = LuceneProperties.getSearchDirs();
		for (Object dir : searchDirs) {
			Map<String, Integer> fileCounts = new FileSearcher().searchAndCount((String) dir);
			for (Entry<String, Integer> entry : fileCounts.entrySet()) {
				LOGGER.info(entry.getKey() + ":" + entry.getValue());
			}

			List<String> files = new FileSearcher().search((String) dir);
			for (String path : files) {
				LOGGER.info(path);
			}
		}
	}

}
